<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:device:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleDistribute"
          v-hasPermi="['device:device:edit']"
        >分配企业</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:device:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="设备编号" align="center" prop="code" />
      <!-- <el-table-column label="所属系列" align="center" prop="seriesName" /> -->
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="在线状态" align="center" prop="inline" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.online_status" :value="scope.row.inline"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="lastReceiveStatusTime" width="180"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:device:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-data-line"
            @click="getDeviceInfo(scope.row)"
            v-hasPermi="['device:device:edit']"
          >获取设备信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-male"
            @click="updateSerialIo(scope.row)"
            v-hasPermi="['device:device:edit']"
          >配置串口</el-button>      -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="copyConfig(scope.row)"
            v-hasPermi="['device:device:edit']"
          >复制配置</el-button>         
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <el-dialog title="复制设备配置" :visible.sync="configOpen" width="500px">
      <div class="block">
          <div style="padding: 14px;">
            <img :src="getSensorIcon(form.icon)" style="width: 30px;height: 30px;vertical-align: middle;" alt="">
            <span style="display:block">{{form.name}}</span>
            <time class="time">{{ form.code }}</time>
          </div>
      </div>
      <div class="block">
        <el-tag v-for="tag in configList" :key="tag.name" closable @close="handleRemTag(tag)"> {{tag.name}} </el-tag>
        <i class="el-icon-plus avatar-uploader-icon" v-if="configList.length == 0" @click="openSelectDevice"></i>
      </div>
      <div slot="footer" class="dialog-footer" align="right" style="margin-top:15px">
          <el-button type="primary" @click="confirmCopyConfig(0)">全部设备</el-button>
          <el-button type="primary" @click="confirmCopyConfig(1)">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px">
      <el-dialog title="添加传感器" :visible.sync="addSensorPopup" width="800px" append-to-body>
        <div style="font-size: 13px;margin-bottom: 10px;">请选择传感器类型</div>
        <el-table :data="sensorTypes" @selection-change="handleSelectSensor" height="400">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="显示图标" align="center" prop="icon" width="100">
            <template slot-scope="scope">
              <el-image style="width: 40px; height: 40px" :src="scope.row.icon?(iconBaseUrl+scope.row.icon):''" fit="contain"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="串口名称" align="center" prop="name" />
          <el-table-column label="串口标识" align="center" prop="flag" />
          <el-table-column label="控制类型" align="center" prop="flag" >
            <template slot-scope="scope">
              {{ scope.row.control === 1 ? '输出':'输入' }}
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="targetSensorTypes.length<=0" @click="selectSensor">确 定</el-button>
          <el-button @click="addSensorPopup=false">取 消</el-button>
        </div>
      </el-dialog>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="设备编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备编号" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="分配企业" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择分配企业">
            <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在国家" prop="countryId">
          <el-select v-model="form.countryId" placeholder="请选择国家">
            <el-option v-for="item in countryList" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属系列" prop="deviceTypeId">
          <el-select v-model="form.deviceTypeId" placeholder="请选择所属系列">
            <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属分组" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" @onSelect="monitor" :show-count="true" placeholder="请选择所属分组" style="width: 630px;"/>
        </el-form-item>
        <el-form-item label="设备管理员" prop="masterId">
          <el-input v-model="form.masterName" placeholder="请选择设备管理员" style="width: 300px;">
            <el-button size="mini" type="text" @click="onOpen" style="padding:0 15px 0 15px;" slot="append">选择用户</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input readonly v-model="form.address" placeholder="请选择地址" style="width: 530px;">
            <el-button slot="append" @click="POISearchDialog">选择经纬度</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="脚本" prop="script">
          <el-input  type="textarea" v-model="form.script" placeholder="请输脚本" :rows="8" style="width: 1200px;"/>
        </el-form-item>
        <el-form-item label="传感器" prop="sensor" style="width: 100%;" v-if="false">
          <el-button type="primary" style="width: 160px;" @click="addSensor" :disabled="!form.series" >添加</el-button>
          <div class="sensor-list">
            <div class="sensor-item" v-for="(item,key) in form.sensorList" :key="key">
              <div class="sensor-form">
                <el-input v-model="item.name"  placeholder="传感器名称" style="width: 200px;margin-right: 10px;" />
                <el-input v-model="item.flag"  placeholder="传感器标识" disabled style="width: 200px;margin-right: 10px;" />
                <!-- <el-select v-model="item.dataType" placeholder="请选择控制方式" style="width: 200px;margin-right: 10px;">
                  <el-option 
                    v-for="dict in dict.type.series_data_type"
                    :label="dict.label"
                    :value="dict.value" 
                    :key="dict.value" />
                </el-select> -->
                <el-select v-if="item.dataType==='010'" v-model="item.decimalLength" placeholder="小数位" style="width: 120px;margin-right: 10px;">
                  <el-option  label="0(小数位)" :value="0" />
                  <el-option  label="1(小数位)" :value="1" />
                  <el-option  label="2(小数位)" :value="2" />
                  <el-option  label="3(小数位)" :value="3" />
                  <el-option  label="4(小数位)" :value="4" />
                </el-select>
                <el-input v-if="item.dataType==='010'" v-model="item.unit"  placeholder="单位" style="width: 80px;margin-right: 10px;" />
                <el-input placeholder="串口" type="number" v-model.number="item.sort" :min="1" v-if="!(item.control===2 || (item.id!=null &&!item.sort))" style="width: 80px;margin-right: 20px;" />
                <div class="icon-wrap">
                  <el-upload  style="width: 100%" class="avatar-uploader"
                    :headers="{ Authorization: token }" :action="uploadURL" 
                    :on-success="(res,file)=>{uploadSuccess(key,res,file)}" :multiple="false" accept="image/jpg,image/png,image/jpeg" :limit="1"
                    :show-file-list="false"
                    :file-list="fileList">
                    <el-image :src="item.icon?(iconBaseUrl+item.icon):''" fit="contain" style="width: 100%;height: 100%;" ></el-image>
                  </el-upload>
                </div>
                <div style="display: inline-block;vertical-align: middle;transition: all .2s;" :class="[!!mapping[item.id]?'mapping':'']">
                  <i class="el-icon-share" @click="handleToggle(item.key||item.flag)"  style="cursor: pointer;font-size: 36px;vertical-align: middle;" ></i>
                </div>
                <el-button type="danger" style="width: 60px;margin-left: 20px;" @click="delSensor(key)">删除</el-button>
              </div>
              <div class="sensor-data" v-show="!!mapping[item.flag]" >
                <div class="yingshe-btns">
                  <el-button slot="reference" type="primary" size="mini" style="margin-right: 5px;"  @click="addMapping(key)">添加映射</el-button>
                </div>
                <div class="yingshe-list">
                  <el-row style="text-align: center;" v-show="item.sensorDisplayList&&item.sensorDisplayList.length>0">
                    <el-col :span="2">优先级</el-col>
                    <el-col :span="4">显示条件</el-col>
                    <el-col :span="4">显示单位</el-col>
                    <el-col :span="4">计算公式</el-col>
                    <el-col :span="3">保留小数点后</el-col>
                    <el-col :span="4">类型</el-col>
                    <el-col :span="3">操作</el-col>
                  </el-row>
                  <div class="yingshe-item" v-for="(sub,sub_key) in item.sensorDisplayList" :key="sub_key">
                    <el-row style="text-align: center;">
                      <el-col :span="2">
                        <el-input-number v-model="sub.priority" :min="1" :max="10" label="请输入优先级" style="width: 100px;"></el-input-number>
                      </el-col>
                      <el-col :span="4">
                        <el-input v-model="sub.conditions" placeholder="请输入显示条件"  style="width: 150px;"/>
                      </el-col>
                      <el-col :span="4">
                        <el-input v-model="sub.unit" placeholder="请输入显示单位" style="width: 150px;"/>
                      </el-col>
                      <el-col :span="4">
                        <el-input v-model="sub.formula" placeholder="请输入计算公式" style="width: 150px;"/>
                      </el-col>
                      <el-col :span="3">
                        <el-input-number style="width: 100px;" v-model="sub.pointLength" :min="0" :max="4" label="位"></el-input-number>&nbsp;&nbsp;位
                      </el-col>
                      <el-col :span="4">
                        <el-select v-model="sub.type" placeholder="请选择类型" style="width: 150px;">
                          <el-option
                            v-for="dict in dict.type.monitor_display_type"
                            :key="dict.value"
                            :label="dict.label"
                            :value="parseInt(dict.value)"
                          ></el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="3">
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-delete"
                          @click="delMapping(key,sub_key)"
                        >删除</el-button>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配企业" :visible.sync="distOpen" width="85%">
        <el-form ref="distForm" :inline="true" :model="distForm" :rules="distRules" label-width="120px">
            <el-form-item label="分配企业" prop="id">
                <el-select v-model="distForm.id" placeholder="请选择分配企业">
                    <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属分组" prop="deptId">
                <treeselect v-model="distForm.deptId" :options="deptOptions" @onSelect="monitor" :show-count="true" placeholder="请选择所属分组" style="width: 240px;"/>
            </el-form-item>
            <el-form-item label="已选择的设备" prop="">
                <div style="margin: 0px 0 0 25px">
                    <el-tag
                    style="margin-right: 10px;"
                    v-for="tag in selectDeviceList"
                    :key="tag.name"
                    closable
                    @close="closeTag"
                    type="info">
                    {{tag.name}}
                    </el-tag>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDistForm">确 定</el-button>
        <el-button @click="distOpen=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择设备地图 -->
    <el-dialog width="85%" center title="选择经纬度" :visible.sync="innerVisible" :close-on-click-modal="false" append-to-body>
      <div>
        <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
          <!-- <el-input id="tipInput" v-model="poiKeywords" placeholder="请输入搜索名称"> -->
          <div>通过点击地图选择经纬度</div>
          <el-autocomplete class="inline-input" size="small" v-model="poiKeywords" :fetch-suggestions="querySearch"
            placeholder="请输入搜索名称" @select="handleSelect"></el-autocomplete>
        </div>
        <!-- <el-button slot="append" icon="el-icon-search" @click="searchKeyword" style="width:60px"></el-button> -->
        <!-- </el-input> -->
        <div ref="mapContainer" style="height:600px"></div>
        <div slot="footer" class="dialog-footer" align="right" style="margin-top:15px">
          <el-button type="primary" @click="confirmSelectAdress(1)">确 定</el-button>
          <el-button @click="confirmSelectAdress(0)">取 消</el-button>
        </div>
    </div>
  </el-dialog>

  <select-device ref="selectDevice" :companyId="this.queryParams.companyId" :type="this.form.type" @ok="handleSelectDevice" :id="form.id"></select-device>
  <select-user @ok="onSelect" ref="selectUser" ></select-user>
</div>
</template>

<script>

import selectDevice from "./selectDevice";
import { getToken } from '@/utils/auth'
import { optionSites } from "@/api/site/site";
import { optionSeries } from "@/api/device/series";
import { companyOptions } from "@/api/ztIot/company";
import { managerList, getDevice, delDevice, addDevice, updateDevice,seriesIoOptions ,autoConfigurationSerialIO,getDeviceInfo,updateSerialIo,copyConfig,changeCompany} from "@/api/device/device";
import { deviceTypeOptions } from "@/api/device/deviceType";
import {options} from "@/api/system/country"
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AMapLoader from "@amap/amap-jsapi-loader";
import loadAMap from '@/utils/loadMap'
import selectUser from "../../system/user/selectUser";
export default {
  name: "Device",
  dicts: ['series_data_type','monitor_display_type','online_status'],
  components: { selectDevice,Treeselect,selectUser},
  data() {
    return {
      token:'',
      //地图实例
      map:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      innerVisible:false,
      configOpen:false,
      overwriteUpdate:false,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      siteList:[],//
      seriesList:[],//系列下拉列表
      configList:[],
      companyList:[],
      deviceTypeList:[],
      deptOptions:[],
      countryList:[],
      // 弹出层标题
      title: "",
      poiKeywords: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        code: null,
        type: null,
        ipaddr: null,
        port: null,
        companyId: null,
        siteId: null,
        longitude: null,
        latitude: null,
        address: null,
        inline: null,
        inlineTime: null,
        lastReceiveStatusTime: null,
        tags: null,
        state: null,
        series: null,
        sensorList:[],
        countryId:null,
        masterId:null,
        masterName:null
      },
      configForm:{},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        // type: [
        //   { required: true, message: "设备类型不能为空", trigger: "change" }
        // ],
        // series: [
        //   { required: true, message: "所属系列不能为空", trigger: "change" }
        // ],
        // address: [
        //   { required: true, message: "地址不能为空", trigger: "blur" }
        // ],
        // createTime: [
        //   { required: true, message: "创建时间不能为空", trigger: "blur" }
        // ],
      },
      distRules:{
        id: [
          { required: true, message: "所属企业不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属分组不能为空", trigger: "blur" }
        ]
      },
      //映射隐藏切换
      mapping:{},
      //图片上传
      fileList:[],
      iconBaseUrl:process.env.VUE_APP_BASE_API+'/system/files/anonymous/download/',
      uploadURL: process.env.VUE_APP_BASE_API + '/system/files?module=image',
      //选择传感器弹窗
      addSensorPopup:false,
      //传感器类型列表
      sensorTypes:[],
      //选择的传感器类型
      targetSensorTypes:'',
      //是否是编辑
      isEdit:false,
      //分配
      distOpen:false,
      // 分配表单参数
      distForm: {
        id: null,
        deptId: null,
      },
      selectDeviceList:[]
    };
  },
  created() {
    this.queryParams.companyId = this.$route.query.companyId;
    this.token = 'Bearer ' + getToken();
    this.getOptionSeries()
    this.getOptionSites()
    this.getList();
    this.getCompanyList();
    this.getDeviceTypeList()
    this.getTreeselect()
    this.getCountrys()
  },
  mounted(){
    this.initMap()
  },
  methods: {
    async initMap() {
      const AMap = await loadAMap()
      this.map = new AMap.Map(this.$refs.mapContainer, {
        resizeEnable: true,
        zoom: 16, //初始化地图级别
        showIndoorMap: false,
      })
      AMap.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar'], () => {
        const Scale = new AMap.Scale()
        const toolBar = new AMap.ToolBar({
          position: 'RB',
          offset: new AMap.Pixel(150, 220)
        })
        const controlBar = new AMap.ControlBar()
        // const geolocation = new AMap.Geolocation({
        //   // 是否使用高精度定位，默认：true
        //   enableHighAccuracy: true,
        //   // 设置定位超时时间，默认：无穷大
        //   timeout: 10000,
        //   // 定位按钮的停靠位置的偏移量
        //   offset: [20, 100],
        //   //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        //   zoomToAccuracy: true,
        //   //  定位按钮的排放位置,  RB表示右下
        //   position: "RB",
        // });
        this.map.addControl(controlBar)
        this.map.addControl(toolBar)
        this.map.addControl(Scale)
      })
    },
    //查询所属国家列表
    getCountrys(){
      options().then( res => this.countryList = res.data)
    },
    //获取传感器定义
    getSeriesIoOptions(seriesId){
      seriesIoOptions(seriesId).then(res=>{
        this.sensorTypes = res.data;
      })
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      managerList(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    //查询场地下拉列表
    getOptionSites(){
      optionSites().then( res => this.siteList = res.data)
    },
    //查询设备所属系列下拉列表
    getOptionSeries(){
      optionSeries().then( res => this.seriesList = res.data)
    },
    //企业下拉列表
    getCompanyList(){
      companyOptions().then( res => this.companyList = res.data )
    },
    //设备类型列表
    getDeviceTypeList(){
      this.deviceTypeList = [];
      deviceTypeOptions().then( res => this.deviceTypeList = res.data )
    },
    autoConfigurationSerialIO(){
      this.$modal.confirm('是否全量下发配置到设备端？').then(function() {
        autoConfigurationSerialIO();
      }).then(() => {
        this.$modal.msgSuccess("配置下发成功!");
      }).catch(() => {});
    },
    //获取设备信息
    getDeviceInfo(row){
      getDeviceInfo(row.id).then( res => this.$modal.msgSuccess("操作成功!"));
    },
    //更新串口配置
    updateSerialIo(row){
      updateSerialIo().then( res => this.$modal.msgSuccess("操作成功!"));
    },
    //复制设备配置
    copyConfig(row){
      this.configList = []
      this.configOpen = true;
      this.form = row;
    },
    //确认复制配置
    openSelectDevice(){
      this.configList = [];
      this.$refs.selectDevice.show();
    },
    handleSelectDevice(objArray){
      console.log(objArray)
      this.configList = objArray;
    },
    handleRemTag(tag){
      this.configList = this.configList.filter( o => o.id != tag.id)
    },
    //确认复制配置
    confirmCopyConfig(type){
      let param = {id:this.form.id,type:this.form.type,companyId:this.form.companyId,overwriteUpdate:true}
      if(type===1){
        param.deviceList = this.configList;
        if(this.configList.length == null){
          this.$modal.msgError("请选择复制到设备!")
          return false ;
        }
      }
      this.$modal.loading("正在复制参数，请稍后....");
      copyConfig(param).then(res => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess("操作成功!")
        this.configOpen = false ;

      });
    },
    // 取消按钮
    cancel() {
      this.configOpen = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        type: null,
        ipaddr: null,
        port: null,
        companyId: null,
        siteId: null,
        longitude: null,
        latitude: null,
        address: null,
        inline: null,
        inlineTime: null,
        lastReceiveStatusTime: null,
        tags: null,
        state: null,
        series: null,
        sensorList:[],
        countryId:null,
        masterId:null,
        masterName:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.items = selection.map(item => item)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.mapping = {};
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
     /** 分配按钮操作 */
    handleDistribute(row){
        this.distOpen = true;
        this.selectDeviceList = row.id || this.items
        this.distForm = {}
    },
    submitDistForm(){
        this.$refs["distForm"].validate(valid => {
        if (valid) {
            let companyId = this.distForm.id
            let deptId = this.distForm.deptId
            let deviceList = this.selectDeviceList.map((item) => {
                return {id:item.id,code:item.code};
            })
            changeCompany({companyId,deptId,deviceList}).then(res => {
                this.$modal.msgSuccess("分配成功");
                this.distOpen = false;
                this.distForm = {}
            });
        }
      });
    },
    closeTag(item){
        let index = this.selectDeviceList.findIndex(i=>i.id===item.id);
        this.selectDeviceList.splice(index,1)
      },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.mapping = {};
      this.reset();
      this.isEdit = true;
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let params = JSON.parse(JSON.stringify(this.form))
            params.sensorList.forEach(el=>{delete el.id})
            addDevice(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + row.code + '"的数据项？').then(function() {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    querySearch(queryString, cb) {
      this.autoComplete.search(queryString, (status, result) => {
        var tips = result.tips || [];
        tips = tips.map(it => {
          it.value = it.name
          return it
        })
        // 调用 callback 返回建议列表的数据
        cb(tips);
      })
    },
    handleSelect(item) {
      this.placeSearch.setCity(item.adcode);
      this.placeSearch.search(item.name);
    },
    confirmSelectAdress(type) {
      // 确定
      if (type === 1) {
        if (this.currentSelectAddress) {
          const result = this.currentSelectAddress
          const { formattedAddress, addressComponent } = result
          const { location, province, city, district } = addressComponent
          this.form.longitude = location.lng
          this.form.latitude = location.lat
          this.form.address = formattedAddress
        }
      }
      this.innerVisible = false
    },
    POISearchDialog() {
      let _this = this;
      this.innerVisible = true
      this.currentSelectAddress = null
      this.poiKeywords = ''
      this.$nextTick(async () => {
        const AMap = await AMapLoader.load({
          key: this.mapConfig.MAPKEY, // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Geolocation"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        });

        this.map = new AMap.Map(this.$refs.mapContainer, {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 12, //初始化地图级别
          // center: [116.405467, 39.907761], //初始化地图中心点位置
        });
        AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation'], () => {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
          })

          function onComplete(res) {
            const pointer = [res.position.lng, res.position.lat]
            // data是具体的定位信息
            _this.map.setCenter(pointer);
          }

          function onError(res) {
            // 定位出错
            console.error(res.message)
          }
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });
          var autoOptions = {
            //city 限定城市，默认全国
            city: '广州',
            input: "tipinput"
          };
          // 实例化AutoComplete
          const geocoder = new AMap.Geocoder()
          this.autoComplete = new AMap.AutoComplete(autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            map: this.map, // 展现结果的地图实例
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          this.placeSearch.on('markerClick', (e) => {
            const { location } = e.data
            geocoder.getAddress(location, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = location
                this.currentSelectAddress = result.regeocode
              }
            })
          })
          // 监听鼠标点击地图点，生成marker
          this.map.on('click', (ev) => {
            if (this.currentMarker) {
              this.map.remove(this.currentMarker);
            }
            const { lng, lat } = ev.lnglat
            var marker = new AMap.Marker({
              icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
              position: [lng, lat],
              offset: new AMap.Pixel(-10, -27),
            });
            this.currentMarker = marker
            this.map.add(marker);
            geocoder.getAddress(ev.lnglat, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = ev.lnglat
                this.currentSelectAddress = result.regeocode
              }
            })
          });
        })
      })

    },

    onOpen(){
      this.$refs["selectUser"].show()
    },
    /** 导出按钮操作 */
    onSelect(obj) {
      console.log(obj)
      if(obj) {
        this.form.masterId = obj[0].userId
        this.form.masterName = obj[0].nickName
      }
    }
,
    //添加传感器
    addSensor(){
      this.addSensorPopup = true
    },
    // 多选框选中数据
    handleSelectSensor(selection) {
      this.targetSensorTypes = selection
    },
    selectSensor(){
      let targets = JSON.parse(JSON.stringify(this.targetSensorTypes))
      let form = JSON.parse(JSON.stringify(this.form))
      let arr = [];
      targets.forEach(el=>{
        let target = form.sensorList.find(v=>v.flag===el.flag)
        console.log(target)
        if(!target){
          arr.push(el)
        }
      })
      form.sensorList = form.sensorList.concat(arr)
      this.form = form;
      this.addSensorPopup = false;
    },
    delSensor(index){
      if(this.form.sensorList.length===1){
        this.$message.error('传感器不能少于一个')
        return
      }
      let sensorList = JSON.parse(JSON.stringify(this.form.sensorList))
      sensorList.splice(index,1)
      this.$set(this.form,'sensorList',sensorList)
    },
    handleToggle(key){
      let mapping = JSON.parse(JSON.stringify(this.mapping))
      if(mapping[key]){
        mapping[key] = false;
      }else{
        mapping[key] = true;
      }
      this.mapping = mapping
    },
    uploadSuccess(key,res, file){
      this.form.sensorList[key].icon = res.data.id;
    },
    addMapping(key){
      let form = JSON.parse(JSON.stringify(this.form))
      if(!form.sensorList[key].sensorDisplayList){
        form.sensorList[key].sensorDisplayList = [];
      }
      form.sensorList[key].sensorDisplayList.push({
        priority:null,
        conditions:null,
        unit:null,
        formula:null,
        pointLength:null,
        type:null
      })
      this.form = form;
    },
    delMapping(key,subKey){
      let form = JSON.parse(JSON.stringify(this.form))
      let sensor = form.sensorList[key]
      sensor.sensorDisplayList.splice(subKey,1)
      this.form = form
    },
    monitor(data){
      this.form.ancestors = data.ancestors
    }
  },
  watch:{
    'form.series'(v){
      if(!this.isEdit){
        //编辑时避免series变化而清空sensorList
        this.form.sensorList = [];
      }
      this.isEdit = false;
      if(v){
        let id = this.seriesList.find(i=>i.code===v).id;
        this.getSeriesIoOptions(id)
      }
    },
    open(v){
      if(!v){
        this.cancel()
      }
    }
  }
};
</script>

<style lang="scss" scoped >
.sensor-list{
  margin-top: 10px;
  width: 1200px;
  .icon-wrap{
    display: inline-block;
    vertical-align: middle;
    width: 36px;
    height: 36px;
    overflow: hidden;
    cursor: pointer;
    margin-right: 10px;
  }
  .mapping{
    transform: rotate(90deg);
    transition: all .2s;
    -webkit-transition: all .2s;
  }
  .sensor-item{
    margin-bottom: 5px;
  }
  .sensor-data{
    position: relative;
    background-color: #fafafa;
    border-radius: 5px;
    border: 1px solid #e6e6e6;
    width: 100%;
    margin-top: 5px;
    transition: all .2s;
    overflow: hidden;
    .yingshe-btns{
      text-align: right;
      padding-top: 5px;
      padding-bottom: 5px;
      padding-right: 10px;
    }
    .yingshe-list{
      width: 100%;
      padding: 0 20px;
      margin-bottom: 20px;
      .yingshe-item{
        padding: 5px 0;
        border-bottom: 1px solid #e1e1e1;
        &:nth-last-child(1){
          border-bottom: none;
        }
      }
    }
  }
}
.icon-select{
  width: 450px;
  padding: 10px;
  .icon-list{
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    .icon-item{
      display: flex;
      flex: 0 0 auto;
      align-items: center;
      justify-content: center;
      width: 70px;
      height: 70px;
      padding: 5px;
      border-radius: 2px;
      border: 1px solid #fff;
      cursor: pointer;
      &:hover{
        border: 1px solid #1890ff;
        color: #1890ff;
      }
    }
  }
}
</style>

<style>
/* 取消[type='number']的input的上下箭头 */
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
 
input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}
 
input[type='number'] {
  -moz-appearance: textfield;
}

.block {
    text-align: center;
    border-right: 1px solid #eff2f6;
    display: inline-block;
    width: 49%;
    box-sizing: border-box;
}
.avatar-uploader-icon {
    font-size: 38px;
    color: #35cece;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    cursor: pointer;
  }
</style>